package com.ark.cloud.dataservices.modules.sys.service.impl;

import com.ark.cloud.dataservices.modules.sys.entity.po.Role;
import com.ark.cloud.dataservices.modules.sys.entity.po.User;
import com.ark.cloud.dataservices.modules.sys.entity.vo.CustomerUserDetails;
import com.ark.cloud.dataservices.modules.sys.service.IRoleService;
import com.ark.cloud.dataservices.modules.sys.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Copyright(c): 2021 Cloud-Ark Inc.
 * Author(s): Ma Wei (mawei@cloud-ark.com)
 */
@Slf4j
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String uniqueId) {

        User user = userService.getByUniqueId(uniqueId);
        log.info("load user by username :{}", user.toString());

        if (user != null) {
            //获取用户的所有权限
            List<Role> permissionList = roleService.query(user.getId());
            //返回自己实现的用户用户信息
            return new CustomerUserDetails(user, permissionList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
